<template>
  <div class="affair-catalog">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>事务库管理</span>
          <div>
            <el-input-number v-model="filterCategory" :min="1" :max="999" placeholder="大类代码" />
            <el-button class="ml8" @click="loadItems" :loading="loading">刷新</el-button>
            <el-button type="primary" class="ml8" @click="openAdd">新增库项</el-button>
          </div>
        </div>
      </template>

      <el-table :data="items" v-loading="loading" style="width: 100%">
        <el-table-column prop="code" label="编码" width="120" />
        <el-table-column prop="categoryCode" label="大类代码" width="120" />
        <el-table-column prop="itemCode" label="事务项编码" width="120" />
        <el-table-column prop="categoryName" label="大类名称" />
        <el-table-column prop="itemName" label="具体事务名称" />
        <el-table-column label="启用" width="100">
          <template #default="{ row }">
            <el-switch v-model="row.active" @change="toggleActive(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" text @click="openEdit(row)">编辑</el-button>
            <el-button type="danger" text @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="showDialog" :title="isEdit ? '编辑库项' : '新增库项'" width="520px" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="大类代码" prop="categoryCode">
          <el-input-number v-model="form.categoryCode" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="事务项编码" prop="itemCode">
          <el-input-number v-model="form.itemCode" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="大类名称" prop="categoryName">
          <el-input v-model="form.categoryName" clearable />
        </el-form-item>
        <el-form-item label="具体事务名称" prop="itemName">
          <el-input v-model="form.itemName" clearable />
        </el-form-item>
        <el-form-item label="编码(自动)" prop="code">
          <el-input v-model="form.code" disabled />
        </el-form-item>
        <el-form-item label="启用" prop="active">
          <el-switch v-model="form.active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { catalogApi } from '@/api/catalog'

export default {
  name: 'AffairCatalog',
  setup() {
    const loading = ref(false)
    const items = ref([])
    const filterCategory = ref(null)

    const showDialog = ref(false)
    const isEdit = ref(false)
    const submitLoading = ref(false)
    const formRef = ref(null)

    const form = reactive({
      id: null,
      categoryCode: null,
      itemCode: null,
      categoryName: '',
      itemName: '',
      code: '',
      active: true
    })

    const rules = {
      categoryCode: [{ required: true, message: '请输入大类代码', trigger: 'change' }],
      itemCode: [{ required: true, message: '请输入事务项编码', trigger: 'change' }],
      categoryName: [{ required: true, message: '请输入大类名称', trigger: 'blur' }],
      itemName: [{ required: true, message: '请输入具体事务名称', trigger: 'blur' }]
    }

    const computeCode = () => {
      if (form.categoryCode && form.itemCode) {
        form.code = `${form.categoryCode}-${form.itemCode}`
      } else {
        form.code = ''
      }
    }

    watch(() => form.categoryCode, computeCode)
    watch(() => form.itemCode, computeCode)

    const loadItems = async () => {
      loading.value = true
      try {
        const resp = await catalogApi.getItems(filterCategory.value ?? undefined)
        items.value = Array.isArray(resp?.data) ? resp.data : []
      } catch (err) {
        ElMessage.error('加载事务库失败')
      } finally {
        loading.value = false
      }
    }

    const openAdd = () => {
      resetForm()
      isEdit.value = false
      showDialog.value = true
    }

    const openEdit = (row) => {
      isEdit.value = true
      showDialog.value = true
      form.id = row.id
      form.categoryCode = row.categoryCode
      form.itemCode = row.itemCode
      form.categoryName = row.categoryName
      form.itemName = row.itemName
      form.code = row.code
      form.active = row.active
    }

    const resetForm = () => {
      form.id = null
      form.categoryCode = null
      form.itemCode = null
      form.categoryName = ''
      form.itemName = ''
      form.code = ''
      form.active = true
      formRef.value?.clearValidate()
    }

    const submit = () => {
      formRef.value.validate(async (valid) => {
        if (!valid) return
        submitLoading.value = true
        try {
          const payload = { ...form }
          let resp
          if (isEdit.value && form.id) {
            resp = await catalogApi.updateItem(form.id, payload)
          } else {
            resp = await catalogApi.addItem(payload)
          }
          if (resp.status === 200) {
            ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
            showDialog.value = false
            loadItems()
          } else {
            ElMessage.error('操作失败')
          }
        } catch (err) {
          ElMessage.error(err?.response?.data?.message || '提交失败')
        } finally {
          submitLoading.value = false
        }
      })
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(`确定删除库项 ${row.code} - ${row.itemName} 吗？`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const resp = await catalogApi.deleteItem(row.id)
          if (resp.status === 204 || resp.status === 200) {
            ElMessage.success('删除成功')
            loadItems()
          } else {
            ElMessage.error('删除失败')
          }
        } catch (err) {
          ElMessage.error(err?.response?.data?.message || '删除失败')
        }
      }).catch(() => {})
    }

    const toggleActive = async (row) => {
      try {
        const payload = { ...row }
        await catalogApi.updateItem(row.id, payload)
        ElMessage.success('状态已更新')
      } catch (err) {
        ElMessage.error('更新状态失败')
        row.active = !row.active
      }
    }

    onMounted(() => {
      loadItems()
    })

    return {
      loading,
      items,
      filterCategory,
      showDialog,
      isEdit,
      submitLoading,
      formRef,
      form,
      rules,
      loadItems,
      openAdd,
      openEdit,
      handleDelete,
      submit,
      toggleActive
    }
  }
}
</script>

<style scoped>
.affair-catalog {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.ml8 { margin-left: 8px; }
</style>